<?php

/**
 * 课程 API
 * User: don
 */

namespace app\modules\app\controllers;

use app\modules\app\models\IntegralBuy;
use app\modules\cn\models\HotActive;
use yii;
use app\libs\AppControl;
use app\libs\Method;
use app\modules\content\models\Classes;
use app\modules\content\models\ClassesSdk;
use app\modules\content\models\VideoLog;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

class CourseController extends AppControl
{

    public $enableCsrfValidation = false;

    function init (){
        parent::init();
        include_once($_SERVER['DOCUMENT_ROOT'].'/../libs/ucenter/ucenter.php');
    }

    /**
     * [actionList 课程列表]
     * @Author don
     * @Date   2021-11-03
     * @return [type]     [description]
     */
    public function actionList()
    {
        // 推荐课程
        $recommendCourse = Classes::find()->where(['showType'=>1,'classesPort'=>2])->orderBy('sort asc,id desc')->limit(4)->asArray()->all();
        if ($recommendCourse) {
            foreach ($recommendCourse as $recommend_key => $recommend_value) {
                $recommendCourse[$recommend_key]['course_tag'] = !empty($recommend_value['course_tag'])?explode(',', $recommend_value['course_tag']):null;
            }
        }

        // 热门课程
        $hotCourse = Classes::find()->where(['showType'=>2,'classesPort'=>2])->orderBy('sort asc,id desc')->limit(4)->asArray()->all();
        if ($hotCourse) {
            foreach ($hotCourse as $hot_key => $hot_value) {
                $hotCourse[$hot_key]['pic'] = "https://www.thinkuprep.com".$hot_value['pic'];
                $hotCourse[$hot_key]['course_image'] = "https://www.thinkuprep.com".$hot_value['course_image'];
                $hotCourse[$hot_key]['course_tag'] = !empty($hot_value['course_tag'])?explode(',', $hot_value['course_tag']):null;

                $hotCourse[$hot_key]['classesSdk'] = ClassesSdk::getClassSdk($hot_value['id']);
            }
        }
        die(json_encode(['code'=>1, 'recommendCourse'=>$recommendCourse, 'hotCourse'=>$hotCourse]));
    }

    /**
     * [actionDetail 课程详情]
     * @Author don
     * @Date   2021-11-03
     * @return [type]     [description]
     */
    public function actionDetail()
    {
        $uid = Yii::$app->session->get('uid');
        // $uid = 3;
        $id = Yii::$app->request->post('id');
        $course = Classes::find()->where(['id'=>$id])->asArray()->one();
        if (!$course) {
            die(json_encode(['code'=>0, 'message'=>'未找到课程信息！']));
        }
        Classes::updateAll(['viewCount' => ($course['viewCount'] + 1)], "id=$id");
        $course['course_tag'] = !empty($course['course_tag'])?explode(',', $course['course_tag']):null;
        // $course['course_description'] = $course['course_description'] ? "https://www.thinkuprep.com".$course['course_description']:null;
        $course['pic'] = $course['pic'] ? "https://www.thinkuprep.com".$course['pic']:null;
        $course['course_image'] = $course['course_image'] ? "https://www.thinkuprep.com".$course['course_image']:null;
        // 详情内容
        $service = !empty($course['service'])?explode(PHP_EOL,$course['service']):null;
        $structure = !empty($course['structure'])?explode(PHP_EOL,$course['structure']):null;
        $course['serviceTitle'] = $course['structureTitle'] = null;
        $course['serviceContent'] = $course['structureContent'] = null;
        if ($service) {
            $course['serviceTitle'] = array_shift($service);
            $course['serviceContent'] = $service;
        }
        if ($structure) {
            $course['structureTitle'] = array_shift($structure);
            $course['structureContent'] = $structure;
        }
        $course['course_description'] = $course['course_description2']?'https://www.thinkuprep.com' . $course['course_description2']:null;

        $classesSdk = ClassesSdk::getClassSdk($id);
        $video = [];
        if ($classesSdk) {
            foreach ($classesSdk as $key => $value) {
                // $videoData = json_decode(Method::post('https://live.thinkwithu.com/api/play/pc-video', ['word'=>$value['sdk']]), true);
                // if ($videoData['code'] == 1) {

                $free = $isPay = 0;
                if($value['type']==2&&$value['integral']>0){
                    //付费
                    $free = 1;
                    $buy = IntegralBuy::videoIsBuyOne($uid,$value['id'],1);//是否购买
                    if($buy) $isPay = 1;
                }
                    $video[] = array(
                        'sdkId' => $value['id'],
                        'name' => $course['name'],
                        'videoUrl' => $value['sdk'],
                        'image' => $value['pic']?Yii::$app->params['thinkUrl'].$value['pic']:'',
                        'type' => $value['type'],
                        'integral' => $value['integral'],
                        'free' => $free,
                        'isPay' => $isPay,
                        'record' => VideoLog::getVideoRecordTime($id, $value['id'], $uid)
                    );
                // } 
            }
            $course['video'] = $video;
        }
        
        die(json_encode(['code'=>1, 'data'=>$course]));
    }

    /**
     * [actionRecord 记录课程播放时间]
     * @Author don
     * @Date   2021-11-03
     * @return [type]     [description]
     */
    public function actionRecord()
    {
        $classesId = Yii::$app->request->post('classesId');  // 公开课 x2_classes的id  试听课 x2_teachers的id 热门活动hot_active
        $sdkId = Yii::$app->request->post('sdkId','');  // 试听课不传
        $record = Yii::$app->request->post('record');  // 时间 秒
        $type = Yii::$app->request->post('type', 1);  // 类型1公开课2试听课3热门活动
        $uid = Yii::$app->session->get('uid');
        // $uid = 3;
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'未登录！']));
        }
        
        $sort = 0;
        if ($type == 1) {
            // 查询课程集数
            $sdkInfo = ClassesSdk::find()->where(['id'=>$sdkId])->asArray()->one();
            $sort = $sdkInfo['sort'];
            // 查询是否已有记录，如果有那么更新record 没有则新增
            $res = VideoLog::find()->where(['uid'=>$uid, 'classesId'=>$classesId, 'sdkId'=>$sdkId,'type'=>$type])->asArray()->one();
            if ($res) {
                $model = VideoLog::findOne($res['id']);
                $model->record = $record;
                $model->updateTime = time();
                if (!$model->save()) {
                    die(json_encode(['code'=>0, 'message'=>'保存观看记录失败！']));
                }
            } else {
                $model = new VideoLog();
                $model->uid = $uid;
                $model->classesId = $classesId;
                $model->sdkId = $sdkId;
                $model->record = $record;
                $model->type = $type;
                $model->sort = $sort;
                $model->createTime = time();
                $model->updateTime = time();
                if (!$model->save()) {
                    die(json_encode(['code'=>0, 'message'=>'保存观看记录失败！']));
                }
            }
        } elseif ($type == 2||$type == 3) {
            // 查询是否已有记录，如果有那么更新record 没有则新增
            $res = VideoLog::find()->where(['uid'=>$uid, 'classesId'=>$classesId,'type'=>$type])->asArray()->one();
            if ($res) {
                $model = VideoLog::findOne($res['id']);
                $model->record = $record;
                $model->updateTime = time();
                if (!$model->save()) {
                    die(json_encode(['code'=>0, 'message'=>'保存观看记录失败！']));
                }
            } else {
                $model = new VideoLog();
                $model->uid = $uid;
                $model->classesId = $classesId;
                $model->sdkId = $sdkId;
                $model->record = $record;
                $model->type = $type;
                $model->sort = $sort;
                $model->createTime = time();
                $model->updateTime = time();
                if (!$model->save()) {
                    die(json_encode(['code'=>0, 'message'=>'保存观看记录失败！']));
                }
            }
        } 
        // VideoLog::deleteAll("uid = :uid AND classesId = :classesId", array(':uid'=>$uid, ':classesId'=>$classesId));
        
        

        die(json_encode(['code'=>1, 'message'=>'保存成功！']));
    }

    /**
     * [actionList 给留学app的雅思课程列表]
     * @Author yoyo
     * @Date   2022-2-08
     * @return [type]     [description]
     */
    public function actionSmartAppList()
    {
        // 推荐课程
        $page = Yii::$app->request->get('page', 1);
        $pageSize = Yii::$app->request->get('pageSize', 10);
        $offset = ($page - 1) * $pageSize;
        $data = Classes::find()->where('isShow=1 and classesPort=2')->orderBy('sort asc,id desc')->offset($offset)->limit($pageSize)->asArray()->all();
        if ($data) {
            foreach ($data as $k => $v) {
                $data[$k]['course_tag'] = !empty($v['course_tag']) ? explode(',', $v['course_tag']) : null;
            }
        }
        die(json_encode(['code'=>1, 'data'=>$data]));
    }

    //课程首页v3.0
    public function actionIndex(){
        // 推荐课程
        $recommendCourse = Classes::find()->where(['showType'=>1,'classesPort'=>2])->orderBy('sort asc,id desc')->limit(4)->asArray()->all();
        if ($recommendCourse) {
            foreach ($recommendCourse as $recommend_key => $recommend_value) {
                $recommendCourse[$recommend_key]['course_tag'] = !empty($recommend_value['course_tag'])?explode(',', $recommend_value['course_tag']):null;
                $recommendCourse[$recommend_key]['pic'] = $recommend_value['pic']?Yii::$app->params['thinkUrl'].$recommend_value['pic']:'';
                $recommendCourse[$recommend_key]['course_image'] = $recommend_value['course_image']?Yii::$app->params['thinkUrl'].$recommend_value['course_image']:'';
            }
        }
        // 热门课程
        $hotCourse = Classes::courseList(2,2);
        die(json_encode(['code'=>1, 'recommendCourse'=>$recommendCourse, 'hotCourse'=>$hotCourse]));
    }

    //v3.0
    public function actionLists(){
        $type = Yii::$app->request->get('type', 1);
        $course = Classes::courseList($type);
        die(json_encode(['code'=>1, 'course'=>$course]));
    }

    //视频购买
    public function actionVideoBuy(){
        $uid = Yii::$app->session->get('uid');
        $id = Yii::$app->request->post('id');//视频id
        $contentId = Yii::$app->request->post('contentId');//内容id
        $type = Yii::$app->request->post('type',1);
        $name = Yii::$app->request->post('name');
        $phone = Yii::$app->request->post('phone');
        if (!$uid) {
            die(json_encode(['code'=>5, 'message'=>'未登录！']));
        }
        $isAll = 0;
        if($type==1){
           if($contentId){
               //全部购买--付费视频
               $isBuy = IntegralBuy::videoIsBuy($uid,$contentId);
               if($isBuy){
                   $buy = implode(',',$isBuy);
               }else{
                   $buy = '0';
               }
               $data = ClassesSdk::find()->where("classesId=$contentId and id not in ($buy) and type=2 and integral>0 and sdk!=''")->asArray()->all();
               if(!$data){
                   die(json_encode(['code'=>0, 'message'=>'暂无付费视频，无需购买']));
               }
               $integral = array_sum(array_column($data,'integral'));
               $id = implode(',',array_column($data,'id'));
               $isAll = 1;
           }elseif($id){
               //单个视频
               $isBuy = IntegralBuy::videoIsBuyOne($uid,$id,1);
               if($isBuy){
                   die(json_encode(['code'=>0, 'message'=>'该课程视频已购买']));
               }
               $data[0] = ClassesSdk::find()->where("id=$id")->asArray()->one();
               $integral = $data[0]['integral'];
               $contentId = $data[0]['classesId'];
           }else{
               die(json_encode(['code'=>0, 'message'=>'缺少参数']));
           }
           $course = Classes::findOne($contentId);
           foreach ($data as $k=>$v){
               $data[$k]['title'] = $course->name;
           }
        }else{
            //活动
            $contentId = $id;
            $isBuy = IntegralBuy::videoIsBuyOne($uid,$id,2);
            if($isBuy){
                die(json_encode(['code'=>0, 'message'=>'该活动已购买']));
            }
            $data[0] = HotActive::find()->where("id=$id")->asArray()->one();
            $integral = $data[0]['integral'];
        }
        $info = ['type'=>$type,'name'=>$name,'phone'=>$phone,'isAll'=>$isAll,'id'=>$id,'contentId'=>$contentId,'integral'=>$integral];
        if($integral<0){
            die(json_encode(['code'=>0, 'message'=>'该内容无需购买']));
        }
        $user = uc_user_integral1($uid);
        if($user['integral']<$integral){
            die(json_encode(['code'=>2, 'message'=>'蜜糖不足，请充值']));
        }
        $tr = Yii::$app->db->beginTransaction();
        try {
            IntegralBuy::goodsBuy($uid,$info,$data);
            $tr->commit();
            die(json_encode(['code'=>1, 'message'=>'购买成功']));
        } catch (\Exception $e) {
            $tr->rollBack();
            die(json_encode(['code'=>0, 'message'=>'购买失败']));
        }
    }
}
